package com.pengpeng.sheepfoldmall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.pengpeng.common.constant.ProductConstant;
import com.pengpeng.common.to.IsHasStockTo;
import com.pengpeng.common.to.SkuReductionTo;
import com.pengpeng.common.to.SpuBoundTo;
import com.pengpeng.common.to.es.SkuEsModel;
import com.pengpeng.common.utils.DateUtils;
import com.pengpeng.common.utils.R;
import com.pengpeng.sheepfoldmall.product.entity.*;
import com.pengpeng.sheepfoldmall.product.feign.CouponFeignClient;
import com.pengpeng.sheepfoldmall.product.feign.SearchFeignClient;
import com.pengpeng.sheepfoldmall.product.feign.WareFeignClient;
import com.pengpeng.sheepfoldmall.product.service.*;
import com.pengpeng.sheepfoldmall.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pengpeng.common.utils.PageUtils;
import com.pengpeng.common.utils.Query;

import com.pengpeng.sheepfoldmall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignClient couponFeignClient;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private WareFeignClient wareFeignClient;

    @Autowired
    private SearchFeignClient searchFeignClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 发布商品
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        // 1.保存spu基本信息pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        //基本属性对拷
        BeanUtils.copyProperties(spuSaveVo,spuInfoEntity);
        //设置时间并保存
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveSpuBaseInfo(spuInfoEntity);

        // 2.保存spu的描述图片（商品介绍）pms_spu_info_desc
        //获取图片集合
        List<String> decript = spuSaveVo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        //设置spuId，当spu保存成功后，会自动往SpuInfoEntity实体类里注入自增id
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        //String.join()方法：将此集合中的元素以逗号分隔返回一个新的字符串
        spuInfoDescEntity.setDecript(String.join(",",decript));
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);

        // 3.保存spu的商品图片集  pms_spu_images
        List<String> images = spuSaveVo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(),images);

        // 4.设置spu的规则参数（基本属性） pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            //设置属性
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            productAttrValueEntity.setAttrId(attr.getAttrId());
            productAttrValueEntity.setAttrValue(attr.getAttrValues());
            productAttrValueEntity.setQuickShow(attr.getShowDesc());
            //基本属性名前端有可能不传，所以最好查询出来再设置
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttrValue(productAttrValueEntities);

        // 5.保存spu的积分信息
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        //先将基本属性对拷：成长积分和购物积分
        BeanUtils.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        //远程调用优惠服务保存spu积分信息
        R r1 = couponFeignClient.saveSpuBound(spuBoundTo);
        if (r1.getCode() != 0){
            log.error("远程保存spu积分信息失败");
        }
        // 6.保存当前spu所对应的所有sku的基本信息
        List<Skus> skus = spuSaveVo.getSkus();
        if (!skus.isEmpty()){
            skus.forEach(sku -> {
                // 6.1 先保存sku的基本信息  pms_sku_info
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku,skuInfoEntity);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                //设置sku的默认图片
                String skuDefaultImg = "";
                for (Images skuImage: sku.getImages()){
                    if (skuImage.getDefaultImg() == 1){
                        skuDefaultImg = skuImage.getImgUrl();
                    }
                }
                skuInfoEntity.setSkuDefaultImg(skuDefaultImg);
                skuInfoService.saveSkuInfo(skuInfoEntity);

                //sku保存成功后，就能自动注入skuId（这里获取是因为下面其他信息保存都需要依赖skuId）
                Long skuId = skuInfoEntity.getSkuId();

                // 6.2保存sku的图片信息pms_sku_images
                List<SkuImagesEntity> skuImagesEntityList = sku.getImages().stream().filter(img -> {
                    return !StringUtils.isEmpty(img.getImgUrl());   //先执行过滤，发布商品时没选中的照片不插入数据库,返回true保留，反之过滤。
                }).map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).collect(Collectors.toList());
                skuImagesService.saveSkuImages(skuImagesEntityList);

                // 6.3保存sku的销售属性等信息pms_sku_sale_attr_value
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = sku.getAttr().stream().map(saleAttr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    BeanUtils.copyProperties(saleAttr,skuSaleAttrValueEntity);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveSkuSaleAttrValue(skuSaleAttrValueEntities);

                //6.4保存sku的优惠、满减等信息
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku,skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                //先判断如果有满减信息或打折信息，再去远程调用，防止多余的rpc操作
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1){
                    R r = couponFeignClient.saveSkuReduction(skuReductionTo);
                    if (r.getCode() != 0){
                        log.error("远程保存sku满减信息失败");
                    }
                }
            });
        }

    }

    /**
     * 保存spu基本信息
     */
    @Override
    public void saveSpuBaseInfo(SpuInfoEntity spuInfoEntity) {
        baseMapper.insert(spuInfoEntity);
    }

    /**
     * spu管理页面，根据搜索条件查询spu列表
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        LambdaQueryWrapper<SpuInfoEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        //以下为可能传进来的查询条件做封装
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            lambdaQueryWrapper.and(wrapper -> {
                wrapper.eq(SpuInfoEntity::getId,Integer.parseInt(key)).or().like(SpuInfoEntity::getSpuName,key);
            });
        }
        //这里使用and内嵌条件加箭头函数的作用是为了将sql语句封装为 (id = 1 or spu_name = "xxx") 这样加括号的形式,
        // 并且在and条件之后再拼接eq条件会自动加入and关键字 brand_id = 1 and (id = 1 or spu_name = "xxx")
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)){
            lambdaQueryWrapper.eq(SpuInfoEntity::getBrandId,brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)){
            lambdaQueryWrapper.eq(SpuInfoEntity::getCatalogId,catelogId);
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)){
            lambdaQueryWrapper.eq(SpuInfoEntity::getPublishStatus,status);
        }


        IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params), lambdaQueryWrapper);

        return new PageUtils(page);
    }

    /**
     * 商品上架
     * @param spuId
     */
    @Override
    public void up(Long spuId) {
        //先根据spuId查询对应所有的sku信息
        List<SkuInfoEntity> skus = skuInfoService.qrySkusBySpuId(spuId);

        //查询当前spu所有可展示的规格属性,用于封装即将存入es的SkuEsModel的attr属性
        List<ProductAttrValueEntity> attrEntities = productAttrValueService.qryEnableSearchAttrBySpuId(spuId);
        List<SkuEsModel.Attrs> skuEsModelAttrsCollect = attrEntities.stream().map(attrEntity -> {
            SkuEsModel.Attrs skuEsModelAttrs = new SkuEsModel.Attrs();
            skuEsModelAttrs.setAttrId(attrEntity.getAttrId());
            skuEsModelAttrs.setAttrName(attrEntity.getAttrName());
            skuEsModelAttrs.setAttrValue(attrEntity.getAttrValue());
            return skuEsModelAttrs;
        }).collect(Collectors.toList());


        //获取商品对应的skuId集合
        List<Long> skuIds = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        Map<Long, Boolean> skuStockMap = null;
        try {
            //发送远程调用，查看是否还有库存
            List<IsHasStockTo> isHasStockTos = wareFeignClient.isHasStock(skuIds);
            //将list集合转为map（key为skuId，value为该sku是否有库存）
            skuStockMap = isHasStockTos.stream().collect(Collectors.toMap(IsHasStockTo::getSkuId,IsHasStockTo::getIsStock));
        } catch (Exception e) {
            log.error("远程调用库存系统查询sku是否有库存失败,原因：{}",e);
        }


        //建立将要上架的商品集合，这些商品要保存到es数据库，供前台搜索
        Map<Long, Boolean> finalSkuStockMap = skuStockMap;  //stream流里引用的数据得是final的
        List<SkuEsModel> upProducts = skus.stream().map(sku -> {
            //组装需要的数据
            SkuEsModel skuEsModel = new SkuEsModel();
            //相同属性对拷
            BeanUtils.copyProperties(sku,skuEsModel);

            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());
            skuEsModel.setHotScore(0L);     //热度评分

            //如果map为null则默认有库存，否则就获取他是否库存
            if (finalSkuStockMap == null){
                skuEsModel.setHasStock(true);
            }else {
                //如果获取为null则为默认：无库存
                skuEsModel.setHasStock(finalSkuStockMap.get(sku.getSkuId())==null?false:finalSkuStockMap.get(sku.getSkuId()));
            }

            //查询品牌信息并设置
            BrandEntity brandEntity = brandService.getById(sku.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());

            //查询分类信息，设置分类名称
            CategoryEntity categoryEntity = categoryService.getById(sku.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());

            //设置提前查询好的商品的规格属性
            skuEsModel.setAttrs(skuEsModelAttrsCollect);

            return skuEsModel;
        }).collect(Collectors.toList());

        //TODO:发送给es库保存
        R r = searchFeignClient.saveProductToElastic(upProducts);
        if (r.getCode() == 0){
            //商品上架成功,则更新此spu的状态和更新时间
            SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
            spuInfoEntity.setId(spuId);
            spuInfoEntity.setPublishStatus(ProductConstant.StateEnum.SPU_UP.getCode());
            spuInfoEntity.setUpdateTime(new Date());

            baseMapper.updateById(spuInfoEntity);
        }else {
            //商品上架失败
            //TODO：接口幂等性，失败重试
        }
    }
}